using System;
using System.Collections.Generic;
using log4net;
using SQLRunnerLib.RunnableItems;
using SQLServices.RunnableItems;

namespace SQLRunnerLib.RunnableItems
{
    /// <summary>
    /// Summary description for RunnableManager.
    /// </summary>
    public class RunnableManager : 
        IRunnableItemsManager
    {

        #region Private Instances

        private List<IRunnableItemOld> _runList;
        private IPathItemOld _defaultPath;
        private static readonly ILog _log = LogManager.GetLogger(typeof(RunnableManager).FullName);

        #endregion
        #region Constructor Methods

        public RunnableManager()
        {
            _runList = new List<IRunnableItemOld>();
        }

        #endregion
        #region Private Methods

        private RunnableItem AddScript(RunnableState state, string name, string error)
        {
            RunnableItem runnableItem = new RunnableItem(state, name, error, _defaultPath);
            _runList.Add(runnableItem);	
            return runnableItem;
        }

        #endregion
        #region Public Methods

        public IRunnableItemOld AddError(string name, string error)
        {
            _log.Debug(String.Format("AddError: name({0}) - error: {1}", name, error));
            return AddScript(RunnableState.EXECUTED_WITH_ERROR, name, error);
        }

        public IRunnableItemOld AddOk(string name)
        {
            _log.Debug(String.Format("AddOk: name({0})", name));
            return AddScript(RunnableState.EXECUTED_OK, name, "");
        }

        public int TotalScripts()
        {
            return _runList.Count;
        }

        public int TotalErrors()
        {
            return Events(true).Count;
        }

        public List<IRunnableItemOld> Events(bool onlyErrors)
        {
            List<IRunnableItemOld> list = new List<IRunnableItemOld>(_runList.Count);
            if (onlyErrors)
            {
                for (int i = 0; i < _runList.Count; i++)
                {
                    if (((RunnableItem) _runList[i]).State == RunnableState.EXECUTED_WITH_ERROR)
                        list.Add(_runList[i]);
                }
            }
            else
            {
                list = _runList;
            }

            return list;
        }

        public void Reset()
        {
            _log.Debug("RunnableManager.Reset method was executed");
            _runList = new List<IRunnableItemOld>();
        }


        #endregion
        #region Properties

        public IPathItemOld DefaultPath
        {
            get { return _defaultPath; }
            set { _defaultPath = value; }
        }
		
        #endregion
    }
}